package com.thread.Concurrent;
/*1、同步的是对象：代码块
 2、锁都是锁的需要修改资源的方法/对象或者class
 3、看上同步以后结果是否正确，看临界资源的边界
 4、哪个线程先执行，取决于cpu的调度，也可能是老婆先取到钱，我余额不足，或者反之；
 5、以下是使用同步资源后：安全的银行
 */

import com.thread.TestYeild.TestJoin;

public class synchronized01 {
    public static void main(String[] args)  {
        synchronized01.Account account = new synchronized01.Account(100, "生活基金");
        synchronized01.Drawing my = new synchronized01.Drawing(account, 20, "我");
        synchronized01.Drawing myWife = new synchronized01.Drawing(account, 10, "老婆");

        my.start();
        myWife.start();

    }
    static class Account {
        int money;//钱
        String purpose;//账户用途
        public Account(int money, String purpose) {
            this.money = money;
            this.purpose = purpose;
        }
    }
    //银行：模拟取款
    static class Drawing extends Thread {
        synchronized01.Account account;//账户
        int drawingMoney;//取出多少钱
        int nowMoney;//当前余额

        //构造方法
        public Drawing(synchronized01.Account account, int drawingMoney, String cardName) {
            super(cardName);//父类的有参构造，要写在方法的最前面
            this.account = account;
            this.drawingMoney = drawingMoney;
        }
        //重写run方法——>取钱
        @Override
        public void run() {
            //synchronized对象是变化的量，增、删、改
            synchronized (account){//同步代码块，需要锁的是account对象。格式：synchronized (account){……}
                //1、判断有没有钱
                if ((account.money - drawingMoney) < 0) {
                    System.out.println("余额不足，无法操作！");
                    return;
                }
                //模拟演示
                try {
                    Thread.sleep(100);//放大问题发生的可能性
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                //卡内余额=卡内余额-取出的钱
                account.money = account.money - drawingMoney;
                //手里的钱
                nowMoney = nowMoney + drawingMoney;
                System.out.println(account.purpose+"余额为：" + account.money+"万");
                //Thread.currentThread().getName() = this.getName()
                System.out.println(this.getName() + "手里的钱：" + nowMoney+"万");
            }

        }
    }
}
